//////////////////////////////////////////////////////////////////////////////////
//   Copyright 2011   Mark Price     mark at epickrram.com                      //
//                                                                              //
//   Licensed under the Apache License, Version 2.0 (the "License");            //
//   you may not use this file except in compliance with the License.           //
//   You may obtain a copy of the License at                                    //
//                                                                              //
//       http://www.apache.org/licenses/LICENSE-2.0                             //
//                                                                              //
//   Unless required by applicable law or agreed to in writing, software        //
//   distributed under the License is distributed on an "AS IS" BASIS,          //
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   //
//   See the License for the specific language governing permissions and        //
//   limitations under the License.                                             //
//////////////////////////////////////////////////////////////////////////////////


package com.epickrram.tool.disruptor.reflect;

import com.epickrram.tool.disruptor.Invoker;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

final class ReflectiveMethodInvoker implements Invoker
{
    private final Method method;

    public ReflectiveMethodInvoker(Method method)
    {
        this.method = method;
    }

    @SuppressWarnings("NullArgumentToVariableArgMethod")
    @Override
    public void invoke(Object implementation, Object[] args)
    {
        try
        {
            final int numberOfParameters = method.getParameterTypes().length;
            if(numberOfParameters == 0)
            {
                method.invoke(implementation, null);
            }
            else
            {
                final Object[] actualArgs = new Object[numberOfParameters];
                System.arraycopy(args, 0, actualArgs, 0, numberOfParameters);
                method.invoke(implementation, actualArgs);
            }
        }
        catch (IllegalAccessException e)
        {
            throw new RuntimeException("Failed to invoke", e);
        }
        catch (InvocationTargetException e)
        {
            throw new RuntimeException("Failed to invoke", e);
        }
    }
}
